<template>
  <div class="detail-container">
    <el-form size="mini" label-width="130px" class="minRoW" :rules="rules" ref="orderForm" :model="orderInfo">
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">基本信息</span>
      </div>
      <el-card shadow="never" style="margin-top:20px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商：" prop="supplierId">
              <el-select size="small" clearable style="width:100%" filterable remote reserve-keyword  :loading="supplierLoading"
                         v-model="orderInfo.supplierId"
                         :remote-method="getSupplierList">
                <el-option :value="item.supplierId" :label="item.supplierName" :key="item.supplierId" v-for="item in supplierList"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发货方式：">
              <el-select size="small" clearable  style="width:100%"  v-model="orderInfo.sendType">
                <el-option value="供方送到需方仓库" label="供方送到需方仓库" key="1"></el-option>
                <el-option value="需方在供方仓库自提" label="需方在供方仓库自提" key="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供方开票日期：" >
              <el-input clearable style="width:100%" v-model="orderInfo.invoice"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="合同公司：" prop="fromCompany">
              <el-select clearable style="width:100%" v-model="orderInfo.fromCompany">
                <el-option :value="item" :label="item" :key="item" v-for="item in fromCompanyList"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交货地点：">
              <el-input clearable style="width:100%" v-model="orderInfo.deliveryCity"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同附加条款：">
              <el-input clearable style="width:100%" v-model="orderInfo.otherRemark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购员：" prop="buyerUserId">
              <el-select clearable style="width:100%" filterable v-model="orderInfo.buyerUserId">
                <el-option
                  v-for="item in userOptionList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运费承担：">
              <el-select clearable style="width:100%" v-model="orderInfo.freightType">
                <el-option value="需方承担运输费用" label="需方承担运输费用" key="1"></el-option>
                <el-option value="供方承担运输费用" label="供方承担运输费用" key="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同性质：" prop="contractNature">
              <el-select v-model="orderInfo.contractNature" size="small" clearable style="width:100%">
                <el-option value="公司政策" label="公司政策" key="1"></el-option>
                <el-option value="采购囤货" label="采购囤货" key="2"></el-option>
                <el-option value="对锁订单" label="对锁订单" key="3"></el-option>
                <el-option value="采购预售" label="采购预售" key="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">商品信息</span>
      </div>
      <el-table
        ref="orderItemTable"
        :data="orderInfo.ordGoodsList"
        style="width: 100%;margin-top: 20px" border>
        <el-table-column label="商品品类" width="160" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="`ordGoodsList.${scope.$index}.categoryId`" :rules="rules.categoryId" label-width="0">
              <el-cascader
                size="small"
                filterable
                @change="changeCategoryId(scope.row, scope.$index)"
                :options="categoryList"
                v-model="scope.row.categoryId" :props="{emitPath:false,value:'categoryId',label:'categoryName'}"></el-cascader>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="商品牌号" align="center"  width="160">
          <template slot-scope="scope">
            <el-form-item :prop="`ordGoodsList.${scope.$index}.sapGoodsId`" :rules="rules.sapGoodsId" label-width="0">
              <el-select
                v-model="scope.row.sapGoodsId"
                placeholder="请选择/输入"
                style="width: 90%"
                filterable
                remote
                reserve-keyword
                :remote-method="(query) => goodsQuerySearch(query, scope.row, scope.$index)"
                @change="changeSapGoodsId(scope.row, scope.$index)"
              >
                <el-option
                  v-for="(item,index) in scope.row.goodsQuerySearchList"
                  :key="index"
                  :label="item.goodsSn"
                  :value="item.sapGoodsId">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="采购单价" width="150" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="`ordGoodsList.${scope.$index}.goodsPrice`" :rules="rules.goodsPrice" label-width="0">
              <el-input v-model="scope.row.goodsPrice" type="number"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="采购数量"   width="100"  align="center">
          <template slot-scope="scope">
            <el-form-item :prop="`ordGoodsList.${scope.$index}.goodsNum`" :rules="rules.goodsNum" label-width="0">
              <el-input v-model="scope.row.goodsNum" type="number"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="数量单位"   width="80"  align="center">
          <template slot-scope="scope"> 吨 </template>
        </el-table-column>
        <el-table-column label="采购金额"   width="100" align="center">
          <template slot-scope="scope">
            {{scope.row | fifnum}}
          </template>
        </el-table-column>
        <el-table-column label="结算方式"   width="100" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="`ordGoodsList.${scope.$index}.goodsSettleType`" :rules="rules.goodsSettleType" label-width="0">
              <el-select  style="width:100%" v-model="scope.row.goodsSettleType">
                <el-option value="现汇" label="现汇" key="1"></el-option>
                <el-option value="承兑" label="承兑" key="2"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="杂费(装卸费)"   width="100" align="center">
          <template slot-scope="scope">
            <el-form-item  label-width="0">
              <el-input v-model="scope.row.goodsConsultation" type="number"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="交货日期" width="220" align="center">
          <template slot-scope="scope">
            <el-form-item  label-width="0" :prop="`ordGoodsList.${scope.$index}.goodsDeliveryDate`" :rules="rules.goodsDeliveryDate" >
              <el-date-picker
                style="width:180px"
                v-model="scope.row.goodsDeliveryDate"
                value-format="yyyy-MM-dd"
                type="date"
                format="yyyy 年 MM 月 dd 日"
              >
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="业务性质" width="220" align="center">
          <template slot-scope="scope">
            <el-form-item  label-width="0" :prop="`ordGoodsList.${scope.$index}.businessType`" :rules="rules.businessType" >
              <el-select v-model="scope.row.businessType" size="small" clearable>
                <el-option value="内销" label="内销" key="1"></el-option>
                <el-option value="出口" label="出口" key="2"></el-option>
                <el-option value="部分出口" label="部分出口" key="3"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="底色" align="center" width="180">
          <template slot-scope="scope">
            <el-form-item  label-width="0">
              <el-select v-model="scope.row.goodsColor" size="small" clearable>
                <el-option value="蓝底透明" label="蓝底透明" key="1"></el-option>
                <el-option value="白底透明" label="白底透明" key="2"></el-option>
                <el-option value="黑底透明" label="黑底透明" key="3"></el-option>
                <el-option value="颜色备注" label="颜色备注" key="4"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="200">
          <template slot-scope="scope">
            <el-form-item  label-width="0">
              <el-input v-model="scope.row.goodsRemark"></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="适配销售订单" align="center" width="460"  fixed="right">
          <template slot-scope="scope">
            <el-form-item :prop="`ordGoodsList.${scope.$index}.crmOrderIds`" :rules="rules.crmOrderIds" label-width="0">
              <el-select
                class="zdy-sec"
                popper-class="zdy-op"
                style="width:420px"
                multiple
                clearable
                v-model="scope.row.crmOrderIds"
                @visible-change="showSel('',scope.row,scope.$index,$event)"
                :loading="crmOrderLoading">
                <el-option
                  v-for="(item,index) in scope.row.orderList"
                  :key="index"
                  :label="'合同编号:'+item.orderSn+',数量:'+item.goodsNum+',发货方式:'+item.sendType+'\n采购报价:'+item.purchasePrice+',采购底价:'+item.purchaseActualPrice"
                  :value="item.orderId">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="是否开票结算" width="100" align="center"  fixed="right">
          <template slot-scope="scope">
            <el-form-item  label-width="0" :prop="`ordGoodsList.${scope.$index}.isOrderSettle`" :rules="rules.businessType" >
              <el-select v-model="scope.row.isOrderSettle" size="small" clearable disabled>
                <el-option :value="1" label="是" :key="1"></el-option>
                <el-option :value="0" label="否" :key="0"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100"  fixed="right">
          <template slot-scope="scope">
            <el-button type="text" v-if="scope.$index > 0" @click="delGoods(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" size="small" style="float:left;margin-top: 20px" @click="addGoods">新增商品</el-button>
      <el-button type="primary" size="small" style="float:left;margin-top: 20px" @click="copyGoods">复制以上商品</el-button>
      <div style="text-align: right;margin-top:20px;font-size:12px;">订单数量：{{goodsAllNum}}<span style="padding-left:20px">订单金额：{{orderAmount}}</span></div>
    </el-form>

    <div style="text-align: center;clear: both;margin-top:20px">
      <el-button @click="goBlack">返 回</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="btnLoading" >提 交</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import store from '@/store';
import {
  purchaseProcess,
  purchaseOrderDetail,
  getOrderUsersList,
} from '@/api/partner';
import { getCrmOrderList } from '@/api/order';
import {mallSnInfo} from '@/api/allInLine/inquiry'
import { supplierListApi,getFromCompanyList,createOrder } from '@/api/company';
import {materialClassTree,getMaterialList} from '@/api/allInLine/goods'
import { validateCommission } from '@/utils/validate';
const defaultForm={
  supplierId:'', //供应商
  sendType:'',//发货方式
  invoice :'',//供方开票日期
  fromCompany :'',//合同公司
  deliveryCity :'',//交货地点
  otherRemark :'',//合同附加条款
  buyerUserId:'',//采购员
  contractNature:'',//合同性质
  freightType:'',//运费承担
  ordGoodsList:[]
};
const defaultItem = {
  goodsQuerySearchList:[],
  crmOrderIds:[],//销售订单id数组
  orderList:[],
  sapGoodsId:'', //牌号id
  categoryId:'',//品类id
  goodsPrice:'',//单价
  goodsNum:'',//数量
  goodsSettleType:'',//结算方式
  goodsConsultation:'',//杂费
  goodsDeliveryDate:'',//交货日期
  goodsColor:'',//底色
  goodsRemark:'',//
  businessType:'',
  isOrderSettle:0,//开票后结算
}
export default {
  name: "addPurchaseOrder",
  data() {
    const isvalidateCrmOrderIds = (rule, value, callback) => {
      if (value.length == 0 && (this.orderInfo.contractNature == '对锁订单' || this.orderInfo.contractNature == '采购预售')) {
        callback(new Error('请选择适配销售订单'))
      } else {
        callback()
      }
    };
    return {
      roles: store.getters.roles ? store.getters.roles : [],
      loading: false,
      btnLoading: false,
      rules: {
        supplierId: [{ required: true, trigger: 'change', message: ' ' }],
        fromCompany:[{ required: true, trigger: 'change', message: ' ' }],
        buyerUserId:[{ required: true, trigger: 'change', message: ' ' }],
        contractNature: [{ required: true, trigger: ['blur', 'change'], message: ' ' }],
        crmOrderIds: [{ required: true, trigger: 'change', validator: isvalidateCrmOrderIds, }],
        categoryId: [{ required: true, trigger: 'chagne', message: ' ' }],
        sapGoodsId: [{ required: true, trigger: 'chagne', message: ' ' }],
        goodsPrice: [{ required: true, trigger: 'blur', message: ' ' }],
        goodsNum: [{ required: true, trigger: 'blur', message: ' ' }],
        goodsSettleType: [{ required: true, trigger: 'chagne', message: ' ' }],
        goodsDeliveryDate: [{ required: true, trigger: 'chagne', message: ' ' }],
        businessType: [{ required: true, trigger: 'chagne', message: ' ' }],
        isOrderSettle:[{ required: true, trigger: 'chagne', message: ' ' }],
      },
      orderInfo:JSON.parse(JSON.stringify(defaultForm)),
      crmOrderLoading:false,
      supplierList:[],
      userOptionList:[],
      fromCompanyList:[],
      categoryList:[],
      supplierLoading:false

    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId',
      'isMange',
    ]),
    goodsAllNum(){
      let sum = 0
      this.orderInfo.ordGoodsList.forEach((el)=>{
        let goodsNum = el.goodsNum ? parseFloat(el.goodsNum) : 0
        sum = sum+goodsNum
      })
      return sum.toFixed(2)
    },
    orderAmount(){
      let sum = 0
      this.orderInfo.ordGoodsList.forEach((el)=>{
        let goodsNum = el.goodsNum ? parseFloat(el.goodsNum) : 0
        let goodsPrice = el.goodsPrice ? parseFloat(el.goodsPrice) : 0
        sum = sum+goodsNum*goodsPrice
      })
      return sum.toFixed(2)
    },
  },
  created() {
    this.getUserOptionList();
    this.getSupplierList();
    this.getcompanyList();
    this.getClassList();
    this.orderInfo = JSON.parse(JSON.stringify(defaultForm))
    this.addGoods()
    this.orderInfo.buyerUserId = this.userId
    if(this.$route.query.mallSn){
      mallSnInfo({mallSn:this.$route.query.mallSn}).then((res)=>{
      this.orderInfo.ordGoodsList = []
      res.list.forEach((ee,index)=>{
        let c = JSON.parse(JSON.stringify(defaultItem))
        c.categoryId = ee.categoryId
        c.sapGoodsId = ee.sapGoodsId
        c.goodsPrice = ee.mallAveragePrice
        c.goodsNum = ee.mallGoodsNum
        c.goodsSn = ee.goodsSn
        c.crmOrderIds = [];
        c.orderList = []
        c.goodsQuerySearchList = []
        ee.detailList.forEach(el=>{
          c.crmOrderIds.push(el.orderId)
          c.orderList.push({
            orderId:el.orderId,
            ogId:el.ogId,
            orderSn:el.orderSn,
            goodsNum:el.goodsNum,
            sendType:el.sendType,
            purchasePrice:el.purchasePrice,
            purchaseActualPrice:el.purchaseActualPrice
          })
        })
        this.orderInfo.ordGoodsList.push(c);
      })
      console.log(this.orderInfo.ordGoodsList)
      this.orderInfo.ordGoodsList.forEach((ee,index)=>{
        this.goodsQuerySearch(ee.goodsSn, ee, index)
      })


      })
    }
  },

  filters: {
    fifnum(item){
      let goodsPrice = item.goodsPrice ? parseFloat(item.goodsPrice) : 0
      let goodsNum = item.goodsNum ? parseFloat(item.goodsNum) : 0
      return (goodsPrice*goodsNum).toFixed(2)
    },
  },
  methods: {
    delGoods(index){
      this.orderInfo.ordGoodsList.splice(index, 1);
    },
    addGoods(){
      let c = JSON.parse(JSON.stringify(defaultItem))
      this.orderInfo.ordGoodsList.push(c)
    },
    copyGoods(){
      let copiedArray = this.orderInfo.ordGoodsList.map(item => ({...item}));
      this.orderInfo.ordGoodsList = this.orderInfo.ordGoodsList.concat(copiedArray)
    },
    //切换品类
    changeCategoryId(scope,index){
      const data1 = JSON.parse(JSON.stringify(scope));
      data1.goodsQuerySearchList = []
      data1.sapGoodsId = ''
      data1.crmOrderIds = []
      data1.orderList = []
      this.orderInfo.ordGoodsList.splice(index, 1, data1);
    },
    //牌号输入匹配
    goodsQuerySearch(queryString, scope, index) {
      if (queryString && queryString != "" && scope.categoryId) {
        getMaterialList({
          keywords: queryString,
          categoryId:scope.categoryId,
          pageNum: 1,
          pageSize: 1000,
        }).then((res) => {
          const data1 = JSON.parse(JSON.stringify(scope));
          data1.goodsQuerySearchList = res.list
          console.log(data1)
          console.log(index)
          this.orderInfo.ordGoodsList.splice(index, 1, data1);
        });
      }
    },

    //切换牌号
    changeSapGoodsId(scope, index){
      const data1 = JSON.parse(JSON.stringify(scope));
      data1.crmOrderIds = []
      data1.orderList = []
      this.orderInfo.ordGoodsList.splice(index, 1, data1);
    },

    //获取品类
    getClassList(){
      materialClassTree({categoryName:''}).then((res)=>{
        this.categoryList = res
      })
    },

    //获取合同公司列表
    getcompanyList(){
      getFromCompanyList().then((res)=>{
        this.fromCompanyList = res
      })
    },
    //获取供应商列表
    getSupplierList(queryString) {
      if (queryString && queryString != "" ) {
        this.supplierLoading = true
        supplierListApi({ pageNum: 1,pageSize: 10000,tab:'all',supplierState:20,supplierName:queryString}).then(response => {
          this.supplierList = response.list;
          this.supplierLoading = false
        }).catch(() => {
          this.supplierLoading = false
        });
      }
    },


    showSel(query, item, index, e) {
      if (e) {
        this.remoteMethod(query, item, index)
      }
    },
    remoteMethod(query, item, index) {
      this.crmOrderLoading = true
      getCrmOrderList({ sapGoodsId: item.sapGoodsId, orderSn: query }).then((res) => {
        let c = JSON.parse(JSON.stringify(this.orderInfo.ordGoodsList[index]))
        c.orderList = res
        this.orderInfo.ordGoodsList.splice(index, 1, c)
        this.crmOrderLoading = false
      }).catch(() => {
        this.crmOrderLoading = false
      })
    },

    //获取员工下拉选项
    getUserOptionList() {
      getOrderUsersList().then((res) => {
        this.userOptionList = res;
      })
    },

    //返回
    goBlack() {
      this.$router.go(-1)
    },

    //确认提交
    handleConfirm() {
      this.$refs['orderForm'].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.orderInfo))
          data.mallSn = this.$route.query.mallSn ? this.$route.query.mallSn : ''
          this.btnLoading = true;
          data.ordGoodsList = [];
          this.orderInfo.ordGoodsList.forEach((el)=>{
            let c = JSON.parse(JSON.stringify(el))
            delete c.goodsQuerySearchList
            delete c.orderList
            data.ordGoodsList.push(c)
          })
          createOrder(data).then(() => {
            this.btnLoading = false;
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.$router.push({name:'purchaseContract'})
          }).catch(() => {
            this.btnLoading = false;
          })
        }else{
          this.$message.error('必填验证失败！')
        }
      })
    },

    //回退
    blackOrder() {

    },


  },
  watch: {

  },
};
</script>
<style>
.zdy-sec .el-select__tags-text{
  width:150px;
  overflow: hidden;
  display: inline-block;
  text-overflow: ellipsis;
  vertical-align: middle;
}
.zdy-op .el-select-dropdown__item{
  height:auto;
  min-height: 34px;
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: pre-line;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  line-height: 16px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  cursor: pointer;
  margin-bottom: 10px;
}
</style>
<style lang="scss" scoped>

.detail-container {
  width: 90%;
  padding: 20px 20px 20px 20px;
  margin: 20px auto;
  .el-card__header{
    background: #f8f8f8;
    .kehu-name{
      display: inline-block;
      font-size:14px;
      vertical-align: middle;
    }
    .kehu-label{
      font-size:12px;
      vertical-align: middle;
      display: inline-block;
      margin-left:15px;
      color: #409eff;
      background: #ecf5ff;
      border: 1px solid #b3d8ff;
      height:24px;
      line-height: 24px;
      padding:0 10px;
      border-radius: 5px;
    }
    .kehu-info{
      text-align: right;
      font-size: 12px;
      color:#333;
      line-height: 20px;
      span{
        padding-left:16px;
      }
    }
  }
  .operate-container {
    background: #F2F6FC;
    height: 80px;
    margin: -20px -20px 0;
    line-height: 80px;
  }
}
.price-block{
  font-size:12px;
  line-height:30px;
  .lab{
    display: inline-block;
    width:100px;
    text-align: right;
  }
  .text{
    display: inline-block;
  }
}
.minRoW .el-form-item{
  margin-bottom:5px;
}
.tongJitable{
  border-left:1px solid #EBEEF5;
  border-top:1px solid #EBEEF5;
  font-size:12px;
  margin-bottom:20px;
  td{
    border-right:1px solid #EBEEF5;
    border-bottom:1px solid #EBEEF5;
    div.tddiv{
      min-height: 30px;
      line-height: 30px;
      padding:0 5px;
      text-align: center;
      white-space:  nowrap
    }
  }
  .bgtd{
    background: #f5f7fa;
  }
}
</style>
